package com.myk.game.lib.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import androidx.annotation.Nullable;
import com.myk.game.lib.R;

/**
 * 触摸状态控件
 */
public class TouchStateView extends androidx.appcompat.widget.AppCompatImageView {

    private Drawable mDrawableNormal;
    private Drawable mDrawablePressed;
    private float lastX,lastY;
    private long lastT;

    public TouchStateView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TouchStateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.TouchStateView);
        mDrawableNormal = mTypedArray.getDrawable(R.styleable.TouchStateView_drawable_normal);
        mDrawablePressed = mTypedArray.getDrawable(R.styleable.TouchStateView_drawable_pressed);
        setBackground(mDrawableNormal);
        mTypedArray.recycle();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            setBackground(mDrawablePressed);
            lastT = System.currentTimeMillis();
            lastX = event.getX();
            lastY = event.getY();
        }
        else if (event.getAction() == MotionEvent.ACTION_UP) {
            setBackground(mDrawableNormal);
            int touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
            float disX = event.getX() - lastX;
            float disY = event.getY() - lastY;
            if (disX * disX + disY*disY < touchSlop * touchSlop){
                if (System.currentTimeMillis() - lastT > ViewConfiguration.getLongPressTimeout()) {
                    performLongClick();
                }
                else {
                    performClick();
                }
            }
        }
        return true;
    }
}
